package cn.com.huzo.service.trade.impl;

import cn.com.huzo.common.util.ApplicationConfiguration;
import cn.com.huzo.model.entities.trade.ProductionInstructionHeaderEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesSuitStyleNoEntity;
import huzofw.model.entities.paginator.Paginator;
import huzofw.service.impl.GenericManagerImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.com.huzo.repository.trade.ProductionInstructionHeaderRepository;
import cn.com.huzo.repository.trade.ProductionInstructionLinesDestinationRepository;
import cn.com.huzo.repository.trade.ProductionInstructionLinesDestinationSchemaRepository;
import cn.com.huzo.repository.trade.ProductionInstructionLinesRepository;
import cn.com.huzo.repository.trade.ProductionInstructionLinesPictureRepository;
import cn.com.huzo.service.trade.ProductionInstructionHeaderManager;
import huzofw.common.util.file.DeleteDirectoryAndFile;
import org.apache.commons.collections4.MapUtils;

/**
 * 生产指示书管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("ProductionInstructionHeaderManager")
public class ProductionInstructionHeaderManagerImpl extends GenericManagerImpl<ProductionInstructionHeaderEntity, Long>
        implements ProductionInstructionHeaderManager {

    private final String uploadPath = (String) ApplicationConfiguration.getProperty("UploadPath_Product"); // 上传路径

    @Resource(name = "ProductionInstructionHeaderRepository")
    private ProductionInstructionHeaderRepository _dao;

    @Resource(name = "ProductionInstructionLinesPictureRepository")
    private ProductionInstructionLinesPictureRepository _dao_lines_picture;

    @Resource(name = "ProductionInstructionLinesRepository")
    private ProductionInstructionLinesRepository _dao_lines;

    @Resource(name = "ProductionInstructionLinesDestinationSchemaRepository")
    private ProductionInstructionLinesDestinationSchemaRepository _dao_lines_schema;

    @Resource(name = "ProductionInstructionLinesDestinationRepository")
    private ProductionInstructionLinesDestinationRepository _dao_lines_destination;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> fetchByHeaderId(Long headerId, Long currentUserId, Long workFlowId) throws Exception {
        Map<String, Object> _result = new HashMap();

        _result.put("HeaderEntity", _dao.fetchByKey(headerId, currentUserId, workFlowId));
        _result.put("PictureList", _dao_lines_picture.fetchAll(headerId));
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(headerId));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(headerId));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(headerId, null));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public Map<String, Object> fetchPrintData(Long headerId, Long currentUserId, Long workFlowId) throws Exception {
        Map<String, Object> _result = new HashMap();

        _result.put("HeaderEntity", _dao.fetchByKey(headerId, currentUserId, workFlowId));
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(headerId));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(headerId));
        _result.put("LinesList", _dao_lines.fetchLinesPrintData(headerId));
        _result.put("ColourList", _dao_lines.fetchProductColourFromMoByHeaderId(headerId));
        _result.put("MaxRowNumPerColour", _dao_lines.fetchMaxRowNumPerColour(headerId));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    @Transactional
    public ProductionInstructionHeaderEntity fetchByStyleNo(String styleNo) throws Exception {
        return _dao.fetchByStyleNo(styleNo);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    public List<ProductionInstructionLinesSuitStyleNoEntity> fetchSuitStyleNoByHeaderId(Long headerId) throws Exception {
        return _dao.fetchSuitStyleNoByHeaderId(headerId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Override
    public List<Map<String, Object>> fetchProductSizeByMoHeaderKeyAndStyleNo(Long headerId, String styleNo) throws Exception {
        return _dao_lines.fetchProductSizeByMoHeaderIdAndStyleNo(headerId, styleNo);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchForPage(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        Long offset = (long) (MapUtils.getInteger(criterion, "Limit") * (MapUtils.getInteger(criterion, "PageIndex") - 1));
        long total = _dao.fetchForCount(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<ProductionInstructionHeaderEntity> itemList = _dao.fetchForPage(criterion);

            Paginator<ProductionInstructionHeaderEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            _result.put("TotalRecordCount", paginator.getTotal());
            _result.put("TotalPages", paginator.getTotalPages());
            _result.put("PageIndex", paginator.getPageIndex());
            _result.put("DataList", paginator.getItemList());
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Long insert(ProductionInstructionHeaderEntity instance) throws Exception {
        // step1: 插入主表并取得主表标识
        Long key = _dao.insert(instance);

        // step2: 插入款号明细
        if (instance.getSuitProductIdList() != null) {
            List<Map<String, Object>> itemList = new ArrayList(instance.getSuitProductIdList().length);
            for (Long ProductId : instance.getSuitProductIdList()) {
                Map<String, Object> item = new HashMap();
                item.put("HeaderId", key);
                item.put("ContractNo", instance.getContractNo());
                item.put("ProductId", ProductId);
                item.put("CreatedBy", instance.getCreatedBy());
                item.put("UpdatedBy", instance.getUpdatedBy());
                itemList.add(item);
            }
            _dao.insertSuitStyleNo(itemList);
        }

        if (key > 0) {
            // 审计日志
            writeAuditLog(instance.getUpdatedBy(), "贸易信息→生产指示书", "款号：" + instance.getSuitStyleNo(), "增加");
        }

        return key;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer update(ProductionInstructionHeaderEntity instance) throws Exception {
        /*
        // step1: 删除款号明细
        _dao.deleteSuitStyleNo(instance.getHeaderId());

        // step2: 插入款号明细
        if (instance.getSuitProductIdList() != null) {
            List<Map<String, Object>> itemList = new ArrayList(instance.getSuitProductIdList().length);
            for (Long ProductId : instance.getSuitProductIdList()) {
                Map<String, Object> item = new HashMap();
                item.put("HeaderId", instance.getHeaderId());
                item.put("ContractNo", instance.getContractNo());
                item.put("ProductId", ProductId);
                item.put("CreatedBy", instance.getCreatedBy());
                item.put("UpdatedBy", instance.getUpdatedBy());
                itemList.add(item);
            }
            _dao.insertSuitStyleNo(itemList);
        }*/
        // step3: 更新生产指示书
        Integer rowsAffected = _dao.update(instance);
        if (rowsAffected > 0) {
            // 审计日志
            writeAuditLog(instance.getUpdatedBy(), "贸易信息→生产指示书", "款号：" + instance.getSuitStyleNo(), "更新");
        }

        return rowsAffected;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        // 删除
        Integer rowsAffected = _dao.delete(MapUtils.getLong(criterion, "HeaderId"));
        // 删除上传的图片及目录
        if (rowsAffected > 0) {
            String dir = uploadPath + MapUtils.getLong(criterion, "HeaderId");
            DeleteDirectoryAndFile.deleteDirectory(dir);

            // 审计日志
            writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"),
                    "贸易信息→生产指示书", "款号：" + MapUtils.getString(criterion, "DeletedStyleNo"),
                    "删除");
        }
        return fetchForPage(criterion);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Integer setOverFlag(Long headerId, Boolean overFlag) throws Exception {
        return _dao.setOverFlag(headerId, overFlag);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<String> fetchStyleNoForAutoComplate(String styleNo) throws Exception {
        return _dao.fetchStyleNoForAutoComplate(styleNo);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> doCheck(Long headerId, Long workFlowId, Short nodeOrder, Long checkedBy, Short isCheckCurrentNode) throws Exception {
        _dao.doCheck(headerId, workFlowId, nodeOrder, checkedBy, isCheckCurrentNode);

        Map<String, Object> _result = new HashMap();
        _result.put("HeaderEntity", _dao.fetchByKey(headerId, checkedBy, workFlowId));
        _result.put("PictureList", _dao_lines_picture.fetchAll(headerId));
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(headerId));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(headerId));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(headerId, null));
        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> doUnCheck(Long headerId, Long workFlowId, Short nodeOrder, Long checkedBy) throws Exception {
        _dao.doUnCheck(headerId, nodeOrder, checkedBy);

        Map<String, Object> _result = new HashMap();
        _result.put("HeaderEntity", _dao.fetchByKey(headerId, checkedBy, workFlowId));
        _result.put("PictureList", _dao_lines_picture.fetchAll(headerId));
        _result.put("ScheduleNode", _dao_lines_schema.fetchScheduleDateNode(headerId));
        _result.put("DestinationNode", _dao_lines_destination.fetchProductionInstructionLinesDestinationNode(headerId));
        _result.put("LinesList", _dao_lines.fetchLinesByHeaderIdAndStyleNo(headerId, null));
        return _result;
    }
}
